package com.example.mybatis.interceptors;

import com.example.mybatis.utils.DataSourceHolder;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

//@Lazy
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class DataSourceInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] oj = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) oj[0];
        if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType()) {
            System.out.println(DataSourceHolder.getDataSource());
            DataSourceHolder.setDataSource(DataSourceHolder.SLAVE_DB);
        } else {
            DataSourceHolder.setDataSource(DataSourceHolder.MASTER_DB);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
